import { useState, useEffect } from "react";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import {
  Button,
  Card,
  CardBody,
  CardHeader,
  Input,
  Checkbox,
  Link,
  Spinner,
} from "@heroui/react";

import AuthLayout from "@/layouts/auth";
import { useUser } from "@/contexts/UserContext";
import { LoginRequest } from "@/types";

export default function LoginPage() {
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [rememberMe, setRememberMe] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [phoneError, setPhoneError] = useState("");
  const [passwordError, setPasswordError] = useState("");
  const navigate = useNavigate();
  const { login: userLogin } = useUser();

  // 页面加载时检查是否保存了记住的登录信息
  useEffect(() => {
    const savedPhone = localStorage.getItem("savedPhone");
    const savedRememberMe = localStorage.getItem("rememberMe") === "true";
    
    if (savedPhone) {
      setPhone(savedPhone);
    }
    setRememberMe(savedRememberMe);
  }, []);

  const validateForm = () => {
    let isValid = true;
    
    // 验证手机号
    if (!phone.trim()) {
      setPhoneError("请输入手机号");
      isValid = false;
    } else if (!/^1[3-9]\d{9}$/.test(phone)) {
      setPhoneError("请输入正确的手机号格式");
      isValid = false;
    } else {
      setPhoneError("");
    }
    
    // 验证密码
    if (!password.trim()) {
      setPasswordError("请输入密码");
      isValid = false;
    } else if (password.length < 6) {
      setPasswordError("密码长度不能少于6位");
      isValid = false;
    } else {
      setPasswordError("");
    }
    
    return isValid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 清除之前的错误信息
    setError("");
    setPhoneError("");
    setPasswordError("");
    
    // 验证表单
    if (!validateForm()) {
      return;
    }
    
    setIsLoading(true);
    
    try {
      // 使用UserContext中的登录方法，传递rememberMe参数
      const success = await userLogin(phone, password, rememberMe);
      
      if (success) {
        // 登录成功后跳转到首页
        console.log("Login successful, navigating to home page");
        navigate("/");
      } else {
        // 登录失败
        setError("登录失败");
      }
    } catch (err: any) {
      console.error("Login failed with error:", err);
      // 根据错误类型显示不同的错误信息
      if (err.message) {
        setError(err.message);
      } else {
        setError("登录失败，请检查手机号和密码");
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <AuthLayout>
      <div 
        className="flex items-center justify-center w-full h-[calc(100vh-56px)] p-4"
        style={{
          backgroundImage: "url('/images/back/login_bg.svg')",
          backgroundSize: "cover",
          backgroundPosition: "center",
          backgroundRepeat: "no-repeat",
        }}
      >
        <div className="flex flex-col w-full max-w-md">
          <Card className="w-full backdrop-blur-sm bg-white/30 dark:bg-black/30">
            <CardHeader className="flex flex-col gap-2 items-center">
              <h1 className="text-2xl font-bold">车辆作业系统</h1>
            </CardHeader>
            <CardBody>
              <form onSubmit={handleSubmit} className="flex flex-col gap-4">
                {error && (
                  <div className="text-danger text-sm">{error}</div>
                )}
                <Input
                  isRequired
                  label="手机号"
                  placeholder="请输入手机号"
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  errorMessage={phoneError}
                  isInvalid={!!phoneError}
                />
                <Input
                  isRequired
                  label="密码"
                  placeholder="请输入密码"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  errorMessage={passwordError}
                  isInvalid={!!passwordError}
                />
                <div className="flex justify-between items-center">
                  <Checkbox
                    isSelected={rememberMe}
                    onValueChange={setRememberMe}
                  >
                    记住我
                  </Checkbox>
                  {/* <Link className="text-sm" href="#">
                    忘记密码?
                  </Link> */}
                </div>
                <Button 
                  color="primary" 
                  type="submit"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <>
                      <Spinner size="sm" color="white" />
                      <span>登录中...</span>
                    </>
                  ) : (
                    "登录"
                  )}
                </Button>
              </form>
              <div className="mt-6 text-center">
                {/* <p className="text-default-500">
                  没有账户?{" "}
                  <RouterLink className="text-primary" to="/register">
                    注册
                  </RouterLink>
                </p> */}
              </div>
            </CardBody>
          </Card>
        </div>
      </div>
    </AuthLayout>
  );
}